﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Remoting;
using System.Text;
using log4net;
using Noesis.Javascript;

namespace XModify
{
    [Serializable]
    public class XModify
    {
        private ILog log = LogManager.GetLogger(typeof(XModify));

        public bool IsDebug
        {
            get;
            set;
        }

        public XModify()
        {
            
        }

        public void Start()
        {
            log.Info("Start:" + DateTime.Now.ToString());

            string[] javascriptFilesArray = Directory.GetFiles("Scripts", "*.js");

            log.Info("SCRIPT FILES COUNT: " + javascriptFilesArray.Length);
            log.Info("SCRIPT FILES: \r\n\t" + string.Join("\r\n\t", javascriptFilesArray));

            if (javascriptFilesArray.Length == 0)
            {
                log.Info("NOT SCRIPT FILES FOR EXCUTE");
                return;
            }

            try
            {
                List<XDocument> documentList = new List<XDocument>();

                foreach (string scriptFile in javascriptFilesArray)
                {
                    XDocument xDocument = Excute(scriptFile);
                    documentList.Add(xDocument);
                }

                foreach (XDocument xDocument in documentList)
                {
                    if (xDocument.SaveChanges)
                    {
                        xDocument.SaveToFile();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Fatal(DateTime.Now.ToString() + ":script run error:", ex);
                Console.WriteLine(ex.Message);

                if (this.IsDebug)
                {
                    Console.ReadKey();
                }
            }
        }

        private XDocument Excute(string scriptFile)
        {
            XDocument xDocument = new XDocument();

            using (JavascriptContext javascriptContext = new JavascriptContext()) 
            {
                javascriptContext.SetParameter("xdocument", xDocument);
                javascriptContext.SetParameter("Console", new XConsole());

                StringBuilder builder = new StringBuilder();

                builder.AppendLine(File.ReadAllText("Function.js"));
                builder.AppendLine(File.ReadAllText(scriptFile));

                javascriptContext.Run(builder.ToString());
            }

            return xDocument;
        }
    }
}
